package trlygjj.tanruiliyigenjinjin.util;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Setter;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import trlygjj.tanruiliyigenjinjin.domain.Employee;
import trlygjj.tanruiliyigenjinjin.domain.SystemLog;
import trlygjj.tanruiliyigenjinjin.service.ISystemLogService;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * Created by user on 2018/7/14.
 */
public class SystemLogAspect {
    @Setter
    private ISystemLogService systemLogService;
    public void write(JoinPoint jp) throws JsonProcessingException {
        //如果是自己的访问,则不写日志
        if(jp.getTarget() instanceof ISystemLogService){
            return;
        }
        SystemLog log = new SystemLog();
        //写入时间
        log.setOptime(new Date());
        //写入当前操作用户
        log.setEmployee((Employee)SecurityUtils.getSubject().getPrincipal());
        //写入访问方法
        log.setFunction(jp.getTarget().getClass().getName());
        //写入访问方法参数
        log.setParams(new ObjectMapper().writeValueAsString(jp.getArgs()));
        //写入ip主机地址
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        log.setOpip(request.getRemoteAddr());
        systemLogService.insert(log);
    }
}
